package com.iweb.servlet;

import com.iweb.constant.LoginAction;
import com.iweb.constant.MyConstant;
import com.iweb.entity.User;
import com.iweb.service.UserService;
import com.iweb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sheng
 * @date 2021/9/19
 * @desc
 */
@WebServlet(name="loginServlet",urlPatterns = {"/login.do","/admin.do"})


public class LoginServlet extends HttpServlet {
  private UserService userService=new UserServiceImpl();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action=req.getParameter("action");
    if(LoginAction.OPEN.equals(action)){
      //打开登录页面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"login.jsp").forward(req,resp);
      return;
    }
    if(LoginAction.DOLOGIN.equals(action)){
      //处理登录表单
      doLogin(req,resp);
      return;
    }
    if(LoginAction.LOGOUT.equals(action)){
      //注销
      return;
    }
    if(LoginAction.INDEX.equals(action)){
      //打开后台首页
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"admin/index.jsp").forward(req,resp);
      return;
    }
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doGet(req,resp);
  }


  /**
   * 处理登录表单
   * @param req
   * @param resp
   */
  private void doLogin(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
    String loginName=req.getParameter("loginName");
    String password=req.getParameter("password");
    try {
      User user= userService.validateUser(loginName,password);
      if(user!=null){
        //验证通过，当前用户信息保存到session
        req.getSession().setAttribute("loginName",user);
        //跳转到后台首页
        resp.sendRedirect(req.getContextPath()+"/admin.do?action="+LoginAction.INDEX);
      }else{
        //设置错误信息
        req.setAttribute("errorMessage","用户名或密码有误");
        //转发到登录页面，显示错误信息
        req.getRequestDispatcher(MyConstant.JSPPREFIX+"login.jsp").forward(req,resp);
      }
    } catch (Exception e) {
      //控制台打印
      e.printStackTrace();
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }
  }
}
